package org.algorithm.biubiu.wheel_1.链表;

import org.algorithm.biubiu.wheel_1.common.ListNode;
import org.junit.Test;

/**
 * @author jiazhaoxin
 * @Date 2022/2/12
 * @Desc {https://leetcode-cn.com/problems/reverse-linked-list-ii/}
 */
public class 反转链表2 {



    @Test
    public void test(){
        ListNode build = ListNode.build(1, 2, 3, 4,5,6,7,8,9);
        System.out.println(ListNode.print(build));
        ListNode listNode = reverseList2(build,2,8);
        String print = ListNode.print(listNode);
        System.out.println(print);
    }

    public ListNode reverseList2(ListNode head, int m, int n) {
        if (head == null || n < m) {
            return null;
        }
        ListNode dummy = new ListNode(-1);
        dummy.next = head;
        head = dummy;

        for(int i =1;i<m;i++){
            head = head.next;
        }
        ListNode prev = head;
        ListNode mNode = prev.next;
        ListNode nNode = mNode;
        ListNode postNode = nNode.next;

        for(int i = m;i<n;i++){
            ListNode next = postNode.next;
            postNode.next = nNode;
            nNode  = postNode;
            postNode = next;
        }
        prev.next = nNode;
        mNode.next = postNode;
        return dummy.next;

    }
}
